package org.lboot.idmo.module.user.role;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.idmo.module.role.SysRole;
import org.lboot.idmo.module.role.SysRoleDAO;
import org.lboot.idmo.module.user.SysUser;
import org.lboot.idmo.module.user.SysUserDAO;
import org.lboot.jpa.jpa.AbstractJpaCurd;
import org.lboot.jpa.jpa.AbstractJpaCurdExt;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class SysUserRoleServiceImpl extends AbstractJpaCurdExt<Long, SysUserRole, SysUserRoleDAO> implements SysUserRoleService{
    SysUserDAO userDAO;

    SysRoleDAO roleDAO;

    @Override
    public List<SysUser> getUsers(Long roleId) {
        List<SysUserRole> res = dao.findByRoleId(roleId);
        List<Long> userIds = res.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
        return userDAO.findByIdIn(userIds);
    }

    @Override
    public List<SysRole> getRoles(Long userId) {
        List<SysUserRole> res = dao.findByUserId(userId);
        List<Long> roleIds = res.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        return roleDAO.findByIdIn(roleIds);
    }

    @Override
    public List<SysUserRole> getByRoleId(Long roleId) {
        return dao.findByRoleId(roleId);
    }

    @Override
    public Boolean isExistMap(Long userId, Long roleId) {
        Optional<SysUserRole> mapOp = dao.findByUserIdAndRoleId(userId,roleId);
        return mapOp.isPresent();
    }

    @Override
    public Optional<SysUserRole> getMap(Long userId, Long roleId) {
        return dao.findByUserIdAndRoleId(userId,roleId);
    }

    @Override
    public void deleteByUserId(Long userId) {
        dao.deleteByUserId(userId);
    }

    @Override
    public void deleteByRoleId(Long roleId) {
        dao.deleteByRoleId(roleId);
    }

    @Override
    public void deleteByUserIds(List<Long> userIds) {
        dao.deleteByUserIdIn(userIds);
    }

    @Override
    public void deleteByRoleIds(List<Long> roleIds) {
        dao.deleteByRoleIdIn(roleIds);
    }

    @Override
    public boolean batchSave(Iterable<SysUserRole> maps) {
        dao.saveAll(maps);
        return true;
    }


}
